#include<cstdio>
#include<cstring>
using namespace std;
class Node{
public:
    char data;
    int curAddr;
    int nextAddr;
    int belongTo;
    Node(char _data, int _curAddr,int _nextAddr):data(_data),curAddr(_curAddr),nextAddr(_nextAddr){
        this->belongTo=-1;
    }
};
int main(){
    Node* mem[100000];
    memset(mem,0,100000*sizeof(Node*));
    int idx1,idx2;
    int N;
    scanf("%d %d %d",&idx1,&idx2,&N);
    int i=0;
    while(i<N){
        int addr,naddr;
        char data;
        scanf("%d %c %d",&addr,&data,&naddr);
        Node* pnode = new Node(data,addr,naddr);
        mem[addr]=pnode;
        i++;
    }
    if(idx1==idx2){
        printf("%05d",idx1);
        return 0;
    }
    while(idx1!=-1){
        Node* node1=mem[idx1];
        node1->belongTo=1;
        idx1=node1->nextAddr;
    }
    while(idx2!=-1){
        Node* node2=mem[idx2];
        if(node2->belongTo==1){
            printf("%05d",node2->curAddr);
            break;
        }
        idx2=node2->nextAddr;
    }
    if(idx2==-1)
        printf("-1");
    return 0;
}
